package project.layer.physical.commands;

import project.layer.physical.Crossroad;
import project.layer.physical.Road;
import project.layer.physical.Truck;
import framework.layer.physical.command.CommandUncompletedException;
import framework.layer.physical.command.IllegalCommandException;
import framework.layer.physical.command.move.MoveCommand;
import framework.layer.physical.entities.vehicles.MoveUncompletedException;

public class MoveForwardCommand extends MoveCommand<Truck, Crossroad, Road> {

	public MoveForwardCommand(Truck truck) {
		super(truck);
	}

	@Override
	public void execute() throws IllegalCommandException, CommandUncompletedException {
		if (getEntity().getPosition().isOnConnection()) {
			try {

				long availableDistance = getEntity().getConnectionPosition().getConnection().getDistanceTillFirstEntityFromEntity(getEntity());
				long connectionLengthLeftDistance = getEntity().getConnectionPosition().getDistanceTillEnd();
				long timeDistance = (long) Math.floor(getEntity().getAvailableTime() * getEntity().getSpeed());
				long wannaDriveDistance = getEntity().getConnectionPosition().getDistanceTillEnd();

				long smallestDistance = Math.min(availableDistance, timeDistance);
				smallestDistance = Math.min(wannaDriveDistance, smallestDistance);
				smallestDistance = Math.min(connectionLengthLeftDistance, smallestDistance);
				smallestDistance = (smallestDistance < 0) ? 0 : smallestDistance;
				
//				long distance = getEntity().getConnectionPosition().getConnection().getLength();
				getEntity().moveOnConnection(smallestDistance, wannaDriveDistance);
			} catch (MoveUncompletedException e) {
				throw new CommandUncompletedException();
			}
		}
	}
}